package impl;

import anaydis.sort.SorterType;
import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class QuickSorterMedianOfThree extends QuickSorterNonRecursive {

    public QuickSorterMedianOfThree(){
        super(SorterType.QUICK_MED_OF_THREE);
    }

    public <T> void sort(Comparator<T> tComparator, List<T> ts){
        List<Integer> pivotes = new ArrayList<Integer>();
        pivotes.add(0);
        pivotes.add(ts.size());
        int i = 0;
        while((i*2)+1<pivotes.size()){
            if(Math.abs(pivotes.get((2*i)+1) - pivotes.get(2*i)) > 2){
                int pivoteAux;       //esta secuencia de if encuentra la mediana de los primeros 3 elementos del arreglo
                int pivoteAux2;
                int pivote;
                int indice;
                if(pivotes.get((2*i)+1) - pivotes.get(2*i) > 0){
                    indice = pivotes.get(2*i);
                }
                else{
                    indice = pivotes.get((2*i)+1);
                }

                if(greater(tComparator, ts, indice, indice+1)){
                    pivoteAux = indice;
                }
                else{
                    pivoteAux = indice+1;
                }
                if(greater(tComparator, ts, indice+1, indice+2)){
                    pivoteAux2 = indice+1;
                }
                else{
                    pivoteAux2 = indice+2;
                }
                if(greater(tComparator, ts, pivoteAux, pivoteAux2)){
                    pivote = pivoteAux2;
                }
                else{
                    pivote = pivoteAux;
                }
                int g = partition(tComparator, ts, pivotes.get(2*i) , pivotes.get((2*i)+1), pivote);
                pivotes.add(pivotes.get(2*i));
                pivotes.add(g);
                pivotes.add(g);
                pivotes.add(pivotes.get((2*i)+1));
            }
            i++;
        }
    }

    /*partition ubica el pivote en su posicion final, y a todos los mayores
    *a el a la derecha y los menores o iguales a izquierda.
    *Return indice final del pivote
    */

    @NotNull
    public SorterType getType(){
        return SorterType.QUICK_MED_OF_THREE;
    }


}
